<template>
  <view class="post-list-container">
    <!-- 搜索栏 -->
    <view class="search-box">
      <u-search placeholder="请输入关键字" v-model="searchKeyword" @search="handleSearch" @custom="handleSearch"></u-search>
    </view>

    <!-- 帖子列表 -->
    <view class="post-list">
      <view
        class="post-card"
        v-for="(post, index) in postList"
        :key="post.id"
      >
        <!-- 帖子头部 -->
        <view class="post-header">
          <image class="avatar" :src="post.user.avatar_url || '/static/default_user.png'" mode="aspectFill" />
          <view class="user-info">
            <text class="username">{{ post.user.nickname }}</text>
<!--            <view class="university-tag">{{ post.university || '-' }}</view>-->
          </view>
        </view>

        <!-- 帖子内容 -->
        <view class="post-content">
          <!-- <text class="post-text">
           
          </text> -->
          <u-read-more font-size="20rpx" color="#333" close-text="查看更多" :toggle="true">
              <rich-text :nodes="post.content"></rich-text>
            </u-read-more>
          <view class="post-images" v-if="getImageArray(post.images).length > 0">
            <image
              class="post-image"
              :src="getImageArray(post.images)[0]"
              mode="aspectFit"
              @click="previewImage(post.images, 0)"
            />
          </view>
        </view>

        <!-- 帖子底部 -->
        <view class="post-footer">
          <text class="post-time">{{ formatTime(post.create_time) }}</text>
          <view class="interaction-buttons">
            <view class="interaction-item" @click="toggleLike(post)">
              <image
                class="like-icon"
                :class="{ 'liked': post.isLiked }"
                :src="post.isLiked ? '/static/post/like.png' : '/static/post/unlike.png'"
                mode="aspectFit"
              />
              <text class="count">{{ post.like_count || 0 }}</text>
            </view>
            <!-- <view class="interaction-item">
              <image
                class="comment-icon"
                src="/static/post/icon_comment.png"
                mode="aspectFit"
              />
              <text class="count">{{ post.comment_count || 0 }}</text>
            </view>
            <view class="interaction-item">
              <image
                class="view-icon"
                src="/static/post/icon_view.png"
                mode="aspectFit"
              />
              <text class="count">{{ post.view_count || 0 }}</text>
            </view> -->
          </view>
        </view>
      </view>
    </view>
    <u-empty text="暂无内容" v-if="postList.length === 0"></u-empty>
    <!-- 加载更多 -->
    <view class="no-more" v-if="!hasMore && postList.length > 0">
      <text>没有更多内容了</text>
    </view>
    <u-tabbar @change="beforeSwitch" active-color="#FFC300" inactive-color="#333" v-model="current" :list="tabbarList" icon-size="55" height="120rpx" :mid-button="false"></u-tabbar>
  </view>

</template>

<script>

export default {
  data() {
    return {
      current: 3,
      postList: [],
      page: 1,
      limit: 10,
      loading: false,
      hasMore: true,
      searchKeyword: ''
    }
  },
  onShow() {
    this.postList = []
    this.page = 1
    this.getPostList()
  },
  onPullDownRefresh() {
    this.refresh()
  },
  onReachBottom() {
    if (this.hasMore && !this.loading) {
      this.loadMore()
    }
  },
  methods: {
    async getPostList() {
      uni.showLoading({
      })
      try {
        const response = await this.$api.getUserPostPage({
          pageNo: this.page,
          pageSize: this.limit,
          content: this.searchKeyword,
          status: 1
        })

        const { list, total } = response
        let _list = list.map(item => {
          return {
            ...item,
            isLiked: item.likes.find(likeItem => likeItem.user_id === this.userInfo.id)
          }
        })
        if (this.page === 1) {
          this.postList = _list
        } else {
          this.postList = [...this.postList, ..._list]
        }

        this.hasMore = this.postList.length < total

      } finally {
        uni.hideLoading()
        uni.stopPullDownRefresh()
      }
    },

    async refresh() {
      this.page = 1
      this.hasMore = true
      await this.getPostList()
    },

    async loadMore() {
      if (this.loading || !this.hasMore) return

      this.page++
      await this.getPostList()
    },

    handleSearch() {
      this.refresh()
    },

    goToPublish() {
      uni.navigateTo({
        url: '/pages/userPost/publish'
      })
    },

    getImageArray(images) {
      if (!images) return []
      return images.split(',').filter(img => img.trim())
    },

    previewImage(images, current) {
      const imageArray = this.getImageArray(images)
      uni.previewImage({
        urls: imageArray,
        current: imageArray[current]
      })
    },

    async toggleLike(post) {
      if (post.isLiked) {
        await this.$api.unlikeUserPost(post.id, { user_id: this.getCurrentUserId() })
        post.like_count--
        post.isLiked = false
      } else {
        await this.$api.likeUserPost(post.id, { user_id: this.getCurrentUserId() })
        post.like_count++
        post.isLiked = true
      }
      uni.hideLoading()
    },

    getCurrentUserId() {
      // 从本地存储或全局状态获取当前用户ID
      return this.userInfo?.id || 1
    },

    formatTime(timeStr) {
      if (!timeStr) return ''

      const date = new Date(timeStr)
      const now = new Date()
      const diff = now - date

      const minute = 60 * 1000
      const hour = 60 * minute
      const day = 24 * hour

      if (diff < minute) {
        return '刚刚'
      } else if (diff < hour) {
        return Math.floor(diff / minute) + '分钟前'
      } else if (diff < day) {
        return Math.floor(diff / hour) + '小时前'
      } else {
        return date.toLocaleDateString()
      }
    }
  }
}
</script>

<style lang="scss">
.post-list-container {
  background-color: #f5f5f5;

.search-box {
  background-color: #fff;
  padding: 24rpx;
}

.post-list {
  display: flex;
  flex-direction: column;
  gap: 20rpx;
}

.post-card {
  background: white;
  border-radius: 12rpx;
  padding: 30rpx;
  margin: 24rpx;
  margin-bottom: 0;
}

.post-header {
  display: flex;
  align-items: center;
  margin-bottom: 25rpx;
}

.avatar {
  width: 80rpx;
  height: 80rpx;
  border-radius: 50%;
  margin-right: 20rpx;
}

.user-info {
  flex: 1;
}

.username {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  display: block;
  margin-bottom: 8rpx;
}

.university-tag {
  background: #f0f0f0;
  color: #666;
  font-size: 24rpx;
  padding: 8rpx 16rpx;
  border-radius: 20rpx;
  display: inline-block;
}

.post-content {
  margin-bottom: 25rpx;
}

.post-text {
  font-size: 28rpx;
  color: #333;
  line-height: 1.6;
  margin-bottom: 20rpx;
  display: block;
  // 五行以内换行,超出省略
  // display: -webkit-box;
  // -webkit-line-clamp: 5;
  // -webkit-box-orient: vertical;
  // overflow: hidden;
}

.post-images {
  margin-top: 20rpx;
}

.post-image {
  width: 100%;
  height: 400rpx;
  border-radius: 15rpx;
}

.post-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.post-time {
  font-size: 24rpx;
  color: #999;
}

.interaction-buttons {
  display: flex;
  gap: 30rpx;
}

.interaction-item {
  display: flex;
  align-items: center;
  gap: 8rpx;
}

.like-icon {
  width: 32rpx;
  height: 32rpx;

  &.liked {
    filter: brightness(1.2);
  }
}

.comment-icon, .view-icon {
  width: 32rpx;
  height: 32rpx;
}

.count {
  font-size: 24rpx;
  color: #666;
}

.load-more, .no-more {
  text-align: center;
  padding: 40rpx;
  color: #999;
  font-size: 28rpx;
}
}

</style>
